const { getTable, setTable, getUnDelData } = require('../../database')
const { STATUS, TABLE } = require('../../utils/constants')
const cryptoPwd = require('../../utils/crypto')
const { format } = require('../../utils/date')

// 根据 id 获取user
async function getUser (req) {
  const id = Number.parseInt(req.params.id)
  const users = await getTable(TABLE.USER)

  const user = users.find(v => v.id === id)

  if (!user) {
    throw new Error('账号不存在')
  }

  return { users, user }
}

// 获取管理员列表
exports.getAdmins = async (req, res, next) => {
  let { page, limit, name, status } = req.query
  page = page ? Number.parseInt(page) : 1
  limit = limit ? Number.parseInt(limit) : 10
  status = ['0', '1'].includes(status) ? Number.parseInt(status) : null

  try {
    let list = await getTable(TABLE.USER)
    const roles = await getUnDelData(TABLE.ROLE)
    const rolesObj = {}
    roles.forEach(v => {
      rolesObj[v.id] = {
        id: v.id,
        name: v.name
      }
    })

    // 筛选
    list = list.filter(v => {
      const filterName = name ? v.account.includes(name) || v.realName.includes(name) : true
      const filterStatus = status !== null ? v.status === status : true

      return filterName && filterStatus && v.isDel === 0
    })

    // 总条数
    const count = list.length

    // 排序并截取
    list = list.sort((a, b) => {
      return b._addTime - b._addTime
    }).slice((page - 1) * limit, page * limit)

    // 格式化时间和提取字段
    list = list.map(({ salt, password, ...user }) => {
      user._lastTime = format(user._lastTime)
      user._addTime = format(user._addTime)
      user._updateTime = format(user._updateTime)

      // 超级管理员角色
      if (user.id === 1) {
        user.roles = roles.map(v => ({
          id: 0,
          name: '超级管理员'
        }))
      } else {
        user.roles = user.roles.filter(id => rolesObj[id]).map(id => rolesObj[id])
      }
      return user
    })

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      data: {
        list,
        count
      }
    })
  } catch (error) {
    next(error)
  }
}

// 添加管理员
exports.createAdmin = async (req, res, next) => {
  const { account, pwd, roles, status, realName } = req.body

  try {
    const users = await getTable(TABLE.USER)

    // 验证账号是否存在
    if (users.some(v => v.account === account)) {
      next(`${account} 已存在`)
      return
    }

    // 生成 id 自增
    let id = 1
    if (users.length > 0) {
      const userIds = users.map(v => v.id).sort()
      id = userIds[userIds.length - 1] + 1
    }

    const now = Date.now()

    const { salt, key } = cryptoPwd(pwd)

    const user = {
      id,
      account,
      salt,
      password: key,
      realName,
      roles,
      status,
      isDel: 0,
      _lastIp: req.ip,
      _lastTime: now,
      _addTime: now,
      _updateTime: now
    }

    users.push(user)

    await setTable(TABLE.USER, users)

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      msg: 'ok'
    })
  } catch (error) {
    next(error)
  }
}

// 修改管理员
exports.updateAdmin = async (req, res, next) => {
  const { roles, status, realName } = req.body

  try {
    const { users, user } = await getUser(req)

    if (user.id !== 1) {
      user.roles = roles
      user.status = status
    }

    user.realName = realName
    user._updateTime = Date.now()

    await setTable(TABLE.USER, users)

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      msg: 'ok'
    })
  } catch (error) {
    next(error)
  }
}

// 获取管理员
exports.getAdmin = async (req, res, next) => {
  try {
    const { user } = await getUser(req)
    const roles = await getUnDelData(TABLE.ROLE)
    const rolesObj = {}
    roles.forEach(v => {
      rolesObj[v.id] = {
        id: v.id,
        name: v.name
      }
    })

    delete user.salt
    delete user.password
    user._lastTime = format(user._lastTime)
    user._addTime = format(user._addTime)
    user._updateTime = format(user._updateTime)

    // 超级管理员角色
    if (user.id === 1) {
      user.roles = roles.map(v => ({
        id: 0,
        name: '超级管理员'
      }))
    } else {
      user.roles = user.roles.filter(id => rolesObj[id]).map(id => rolesObj[id])
    }

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      data: user
    })
  } catch (error) {
    next(error)
  }
}

// 删除管理员
exports.deleteAdmin = async (req, res, next) => {
  try {
    const { users, user } = await getUser(req)

    if (user.id === 1) {
      next(`禁止删除${user.realName}`)
      return
    }

    user.isDel = 1
    user._updateTime = Date.now()
    await setTable(TABLE.USER, users)

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      msg: 'ok'
    })
  } catch (error) {
    next(error)
  }
}

// 修改管理员状态
exports.setAdminStatus = async (req, res, next) => {
  const status = Number.parseInt(req.params.status)

  try {
    const { users, user } = await getUser(req)

    if (user.id === 1) {
      next(`禁止修改${user.realName}状态`)
      return
    }

    user.status = status
    user._updateTime = Date.now()
    await setTable(TABLE.USER, users)

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      msg: 'ok'
    })
  } catch (error) {
    next(error)
  }
}

// 修改管理员密码
exports.setAdminPassword = async (req, res, next) => {
  const { pwd } = req.body

  try {
    const { users, user } = await getUser(req)

    const { key } = cryptoPwd(pwd, user.salt)

    user.password = key
    user._updateTime = Date.now()
    await setTable(TABLE.USER, users)

    // 响应结果
    res.json({
      status: STATUS.SUCCESS,
      msg: 'ok'
    })
  } catch (error) {
    next(error)
  }
}
